<?php

/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/6/14
 * Time: 1:17 PM
 */
namespace Api\Controller;
use Frontend\Helper\SimpleImage;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Velacolib\Utility\Utility;
use Admin\Model\AdminTopicTable;
use Admin\Model\AdminTopic;
use Admin\Model\AdminTopicImg;
use Admin\Model\AdminCommend;
use Zend\Authentication\AuthenticationService;
use Admin\Model\AdminUser;


header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

class TopicController extends AbstractActionController
{
    protected  $auth;
    protected  $topicModel;
    protected $topicImg;
    protected $commentModel;
    protected $userContactTable;
    protected $userModel;
    protected $topicGell;
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        //Utility::CheckLogin($this,'/user/login');

        $this->topicModel = Utility::UserGateway('Admin\Model\AdminTopicTable');
        $this->commentModel = Utility::UserGateway('Admin\Model\AdminCommendTable');
        $this->topicImg = Utility::UserGateway('Admin\Model\AdminTopicImgTable');
        $this->userContactTable = Utility::UserGateway('Admin\Model\AdminUserContactTable');
        $this->userModel = Utility::UserGateway('Admin\Model\AdminUserTable');
        $this->topicGell = Utility::UserGateway('Admin\Model\AdminTopicImgTable');
        return parent::onDispatch($e);
    }

    public function init(){
        //$this->Acl->SetModule('Project');
        //if(!$this->Acl->Check())
        //  $this->redirect()->toRoute('home', array ('action' => 'index'));
    }

    public function indexAction()
    {

        $filter['title'] = $this->params()->fromQuery('title');
        $filter['cat'] = $this->params()->fromQuery('cat');
        $filter['loc'] = $this->params()->fromQuery('loc');
        $filter['type'] = $this->params()->fromQuery('type');
        $filter['user_id'] = $this->params()->fromQuery('user');
        //$filter['ibn'] = $this->params()->fromQuery('ibn');


        $data_topic_count = $this->topicModel->fetch_topic_for_new_user(0,1000);

        $total = count($data_topic_count);
        // How many items to list per page
        $limit = 20;
        // How many pages will there be
        $pages = ceil($total / $limit);
        //current page

        $page = $this->params()->fromQuery('page');
        if($page =='' || $page ==0) $page = 2;
        // Calculate the offset for the query
        $offset = ($page - 1)  * $limit;
        // Some information to display to the user
        $start = $offset;

        $end = min(($offset + $limit), $total);
        $return = array();
        if($page <= $pages){
            $result =  $this->topicModel->filterBy($start,20,$filter);

        }

        echo json_encode($result);
        exit;
    }
    public function addAction(){

            //$this->auth = Utility::CheckLogin($this,'/user/login');
            $topic_id = '';
            $request = $this->getRequest();

            if($request->isPost()){
                //start add topic
                $topic = new AdminTopic();
                $data = $this->params()->fromPost();
                if(isset($data['gel'])){
                    $gellary = $data['gel'];
                    unset($data['gel']);
                }


                $data['status'] = 2;
                $data['create_date'] = date("Y-m-d H:i:s");
                //2592000 = 30 days
                $time_create = strtotime($data['create_date']) + 2592000;
                $data['expire_date'] = date('Y-m-d H:i:s', $time_create);
                if(!isset($data['images'])){
                    $data['images'] = 'no-img.jpg';
                    $data['thumb'] = 'no-img.jpg';
                }else{
                    $data['images'] = $data['images'];
                    $data['thumb'] = $data['images'];
                }
                $data['slug'] = Utility::alphabetconvert($data['title']).'-'.time();
                //echo    $data['create_date'];die;
                $topic->exchangeArray($data);
                $topic_id = $this->topicModel->saveTopic($topic);
                echo $topic_id;
                die;
                //end add topic
                /*
                //start add gallery
                if(isset($gellary))
                {
                    foreach($gellary as $g){
                        $data_gallery = array(
                            'topic_id' => $topic_id,
                            'link' => $g,
                            'user_id' => $this->auth->userid
                        );
                        $topicImgModel = new AdminTopicImg();
                        $topicImgModel->exchangeArray($data_gallery);

                        $tof = $this->topicImg->saveTopicImg($topicImgModel);
                    }
                }
                $this->redirect()->toRoute('frontendtopic',array('action'=>'detail', 'id'=>$topic_id));
                //end add gallery*/
                //echo json_encode(array('topic_id'=>$topic_id, 'auth'=> 1));
                //return new ViewModel(array('topic_id' => $topic_id,'auth'=> 1));
            }
            echo '-1';
            die;
            //return new ViewModel(array('topic_id' => $topic_id,'auth'=> 1));
            //echo json_encode(array('topic_id'=>$topic_id, 'auth'=> 1));
    }
    function editAction(){
    }
    public function detailAction(){
        $topic_id = $this->params()->fromRoute('id',0);
        $arrTopic = $this->topicModel->getTopic($topic_id);
        $image_topic = $this->topicImg->getTopicImgByTopicForApi($topic_id);
        // set the number of items per page to 10
        $user_contact = Utility::GetUserInfo($arrTopic->user_id,'Admin\Model\AdminUserTable');
        $j_topic = json_encode($arrTopic);
        $j_user = json_encode($user_contact);
        $j_img = json_encode($image_topic);
        echo json_encode(array('img'=>$j_img, 'topic'=>$j_topic, 'user' => $j_user ));
        die;
    }
    public function fetchAction($limit = 21){
    }
    public function searchAction(){
        $request = $this->getRequest();
        if (!$request->isXmlHttpRequest()) {
            $search_val = $this->params()->fromPost('search_val');
            $user_array = $this->userModel->searchFullTextArray($search_val);
            $topic_array = $this->topicModel->searchFullTextArray($search_val);
            $return_array = array();
            $return_array['user'] = $user_array;
            $return_array['topic'] = $topic_array;
            //$return_array['search_val'] = $search_val;
            echo json_encode($return_array);
            die;
            } else {
                $search_val = $this->params()->fromQuery('search_val');
                $user_array = $this->userModel->searchFullTextArray($search_val);
                $topic_array = $this->topicModel->searchFullTextArray($search_val);

                $return_array = array();
                $return_array['user'] = $user_array;
                $return_array['topic'] = $topic_array;

                echo json_encode($return_array);
                die;
        }
    }
    /*public function myTopicAction(){

        $user_id = $this->params()->fromQuery('user_id');
        $data_topic_count = $this->topicModel->fetchTopicIndex($user_id,0,1000);
        $total = count($data_topic_count);
        // How many items to list per page
        $limit = ITEM_PER_PAGE;
        // How many pages will there be
        $pages = ceil($total / $limit);
        //current page
        $page =  $this->params()->fromQuery('page');    //$this->params()->fromQuery('page');
        // Calculate the offset for the query
        $offset = ($page - 1)  * $limit;
        // Some information to display to the user
        $start = $offset + 1;

        $end = min(($offset + $limit), $total);
        $data_topic = $this->topicModel->fetchTopicIndex($user_id,$start,$end);


        if($page <= $pages){
            $data_topic = $this->topicModel->fetchTopicIndex($user_id,$start,$end);
            //header("ContentType : application/json");
            echo json_encode($data_topic);
            die;
        }
    }*/
    public function testUploadAction(){
        $file = $this->params()->fromFiles();
        $file_name = $file['fileImg']['name'];
        $file_tmp = $file['fileImg']['tmp_name'];
        $file_size = $file['fileImg']['size'];
        $file_error = $file['fileImg']['error'];
        $file_type = $file['fileImg']['type'];
        $file_type = str_replace('image/','',$file_type);
        $file_name = str_replace('.'.$file_type,'',$file_name);
        $new_name = time().$file_name;

        move_uploaded_file($file_tmp, "./public/upload/image/".$new_name.'.'.$file_type);
        echo $new_name.'.'.$file_type;
        die;
    }
    public function deleteAction(){
        if($this->getRequest()->isPost()){
            $id = $this->params()->fromPost('product_id');
            $this->topicModel->deleteTopic($id);
            echo $id;
            die;
        }
        echo -1;
        die;
    }


    public function addGellaryAction(){
        if($this->getRequest()->isPost()){
            $jdata = $this->params()->fromPost('data');
            //edit case
            $isedit = $this->params()->fromPost('isedit',null);
            $topic_id = $this->params()->fromPost('topic_id', null);

            if($isedit != null){
                if($topic_id != null){
                    $this->topicGell->deleteTopicImgByTopic($topic_id);
                }
            }
            $data = json_decode($jdata);
            foreach($data as $item){
                $item_insert = Array();
                $item_insert['topic_id'] = $item->topic_id;
                $item_insert['user_id']= $item->user_id;
                $item_insert['link'] = $item->link;
                $topic_img = new AdminTopicImg($item_insert);
                $topic_img->exchangeArray($item_insert);
                $this->topicGell->saveTopicImg($topic_img);
            }
            die;
        }
    }

    public function filterByParamAction(){

    }

    public function commentAction(){
        $this->auth = Utility::CheckLogin($this,'/user/login');
        $response = array();
        $post = array();
        $auth = new AuthenticationService();
        $user_id = $auth->getIdentity()->userid;
        $post = $this->params()->fromPost();
        $user =  Utility::GetUserInfo($user_id,'Admin\Model\AdminUserTable');
        $post['user_id'] = $user_id;
        $post['create_date'] = date("Y-m-d H:i:s") ;
        if($post['content'] !='' && (strlen($post['content']) >= 5)){
            $comment = new AdminCommend();
            $comment->exchangeArray($post);
            $this->commentModel->saveCommend($comment);
            $response['result'] = true;
            $response['message'] = 'Comment Success!';

        }else{
            $response['result'] = false;
            $response['message'] = 'The message you have entered is too short!Please lengthen your message to at least 5 characters';
        }
        echo json_encode($response);
        exit;
    }

    /*
     * get topic suspend
     * get user_id
     * return json dta
     * */
    public function getTopicSuspendAction(){
        $user_id= $this->params()->fromQuery('user_id',null);
        $where = array(
            'status'=>2,
            'user_id'=>$user_id
        );
        $data_topic_count = $this->topicModel->getTopicWhere($where,0,1000);
        $total = count($data_topic_count);
        // How many items to list per page
        $limit = ITEM_PER_PAGE;
        // How many pages will there be
        $pages = ceil($total / $limit);
        //current page

        $page = $this->params()->fromQuery('page');
        if($page =='' || $page ==0) $page = 2;
        // Calculate the offset for the query
        $offset = ($page - 1)  * $limit;
        // Some information to display to the user
        $start = $offset;


        if($user_id != null){
            $where = array(
                'status'=>2,
                'user_id'=>$user_id
            );
            $topic_suspend = $this->topicModel->getTopicWhere($where, $start, $limit);
            echo json_encode($topic_suspend);
            die;
        }
        echo '';
        die;



    }
    public function addnologgedAction(){
        if($this->getRequest()->isPost()){
            $data = $this->params()->fromPost();
            $user_class = new AdminUser();
            $data['user']['user_type'] = 2;
            $data['user']['password'] = md5($data['user']['email'].$data['user']['password']);
            $user_class->exchangeArray($data['user']);

            $user_id = $data['topic']['user_id'];
            if($user_id == ''){
                $user_id = $this->userModel->saveUser($user_class);
            }

            if(isset($user_id) && $user_id != null){
                //start add topic
                $topic = new AdminTopic();
                $data = $this->params()->fromPost();
                if(isset($data['topic']['gel'])){
                    $gellary = $data['topic']['gel'];
                    unset($data['topic']['gel']);
                }
                $data['topic']['status'] = 2;
                $data['topic']['create_date'] = date("Y-m-d H:i:s");
                //2592000 = 30 days
                $time_create = strtotime($data['topic']['create_date']) + 2592000;
                $data['topic']['expire_date'] = date('Y-m-d H:i:s', $time_create);
                if(!isset($data['topic']['images'])){
                    $data['topic']['images'] = 'no-img.jpg';
                    $data['topic']['thumb'] = 'no-img.jpg';
                }
                /*else{
                    $data['topic']['images'] = $data['images'];
                    $data['topic']['thumb'] = $data['images'];
                }*/
                //echo    $data['create_date'];die;
                $data['topic']['user_id'] = $user_id;
                $topic->exchangeArray($data['topic']);
                $topic_id = $this->topicModel->saveTopic($topic);
                $user_class->id = $user_id;
                $user_class = $this->userModel->getUser($user_id);
                $array_return['user'] = json_encode($user_class);
                $array_return['topic_id'] = $topic_id;
                echo json_encode($array_return);
                die;
            }
        }
        die;
    }
}